import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torchvision import models
from torch.utils.data import DataLoader

# 检查CUDA是否可用，并设置device变量
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device:", device)

# 数据预处理
transform = transforms.Compose([
    transforms.Resize((224, 224)),  # 调整图像大小以适应ResNet50模型
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])

# 加载数据集
train_dataset = torchvision.datasets.ImageFolder(root=r'D:\develop\PythonCode\python基础\附_项目实战\九_薄膜图片级别分类\lab2_ResNet50\data\train', transform=transform)
test_dataset = torchvision.datasets.ImageFolder(root=r'D:\develop\PythonCode\python基础\附_项目实战\九_薄膜图片级别分类\lab2_ResNet50\data\test', transform=transform)

train_loader = DataLoader(dataset=train_dataset, batch_size=2, shuffle=True, pin_memory=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=1, shuffle=False, pin_memory=True)

# 加载预训练的ResNet50模型
resnet50 = models.resnet50(pretrained=True).to(device)

# 冻结所有卷积层的参数
for param in resnet50.parameters():
    param.requires_grad = False

# 替换最后的全连接层以适应三分类任务
num_ftrs = resnet50.fc.in_features
resnet50.fc = nn.Linear(num_ftrs, 3).to(device)

# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(resnet50.fc.parameters(), lr=0.001)

# 初始化用于跟踪最佳模型的变量
best_accuracy = 0

# 训练和测试模型
num_epochs = 100
for epoch in range(num_epochs):
    resnet50.train()
    for i, (images, labels) in enumerate(train_loader):
        images = images.to(device)
        labels = labels.to(device)

        outputs = resnet50(images)
        loss = criterion(outputs, labels)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i + 1) % 100 == 0:
            print(f'Epoch [{epoch+1}/{num_epochs}], Step [{i+1}/{len(train_loader)}], Loss: {loss.item():.4f}')

    # 测试模型
    resnet50.eval()
    correct = 0
    total = 0
    with torch.no_grad():
        for images, labels in test_loader:
            images = images.to(device)
            labels = labels.to(device)
            outputs = resnet50(images)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()

        accuracy = 100 * correct / total
        print(f'Epoch [{epoch+1}/{num_epochs}] Test Accuracy: {accuracy:.2f}%')

        # 保存最好的模型权重
        if accuracy >= best_accuracy:
            best_accuracy = accuracy
            torch.save(resnet50.state_dict(), 'resnet50_best_model.pth')
            print("Saved Best Model Weights with Accuracy: {:.2f}%".format(accuracy))
